package com.ycfmedical.bed.ui;

import java.util.ArrayList;
import java.util.List;

import com.bilibili.magicasakura.widgets.TintImageView;
import com.tbruyelle.rxpermissions.Permission;
import com.ycfmedical.bed.ApiConfigs;
import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.bean.ImUser;
import com.ycfmedical.bed.event.RefreshEvent;
import com.ycfmedical.bed.listener.SplashView;
import com.ycfmedical.bed.local.DataManager;
import com.ycfmedical.bed.local.entity.User;
import com.ycfmedical.bed.model.VsModel;
import com.ycfmedical.bed.present.SplashPresenter;
import com.ycfmedical.bed.service.LoginImService;
import com.ycfmedical.bed.service.TLSService;
import com.ycfmedical.bed.utils.OrderMsgExecute;
import com.ycfmedical.bed.utils.ResourceUtil;
import com.ycfmedical.bed.widgets.DialogIosAlert;
import com.ycfmedical.bed.wifi.WifiEvent;

import android.Manifest;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.router.Router;

/**
 * Created by Egoist on 2017/3/9.
 */
public class SplashActivity extends XActivity<SplashPresenter> implements SplashView
{

    @BindView(R.id.btn_control)
    TintImageView btnControl;
    @BindView(R.id.btn_userHome)
    TintImageView btnUserHome;
    @BindView(R.id.btn_his)
    TintImageView btnHis;
    @BindView(R.id.btn_phyCharge)
    TintImageView btnPhyCharge;
    @BindView(R.id.btn_life)
    TintImageView btnLife;
    @BindView(R.id.btn_nures)
    TintImageView btnNures;
    @BindView(R.id.btn_entertain)
    TintImageView btnEntertain;
    @BindView(R.id.btn_Healthnews)
    TintImageView btnHealthnews;
    @BindView(R.id.hor_line_one)
    RelativeLayout horLineOne;
    @BindView(R.id.view_mask)
    View viewMask;

    private int LOGIN_RESULT_CODE = 100;

    private final int REQUEST_PHONE_PERMISSIONS = 0;

    WifiEvent wifi = WifiEvent.getInstance();

    public static void launch(Activity activity)
    {
        Router.newIntent(activity).to(SplashActivity.class).launch();
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.activity_splash;
    }

    @Override
    public SplashPresenter newP()
    {
        return new SplashPresenter(this);
    }

    @Override
    public void initData(Bundle savedInstanceState)
    {
        //登录屏蔽
        OrderMsgExecute.loadData("ABBCCD0100270308090002000803080508090906030600");
        User user = DataManager.getInstance().getUser();
        getvDelegate().toastLong("用户正在登录");
        clearNotification();
        initPermissions();
        initImSDK();
        getP().startLoginIm();

//        if (!Kits.Empty.check(DataManager.getInstance().getUser().getImAccount()))
//        {
//            getvDelegate().toastLong("用户正在登录");
//            clearNotification();
//            initPermissions();
//            initImSDK();
//            getP().startLoginIm();
//            btnControl.setEnabled(true);
//            btnUserHome.setEnabled(true);
//            btnHis.setEnabled(true);
//            btnPhyCharge.setEnabled(true);
//            btnLife.setEnabled(true);
//            btnNures.setEnabled(true);
//            btnEntertain.setEnabled(true);
//            btnHealthnews.setEnabled(true);
//            viewMask.setVisibility(View.GONE);
//        }
//        else
//        {
//            getvDelegate().toastLong("当前无用户登录");
//            btnControl.setEnabled(false);
//            btnUserHome.setEnabled(false);
//            btnHis.setEnabled(false);
//            btnPhyCharge.setEnabled(false);
//            btnLife.setEnabled(false);
//            btnNures.setEnabled(false);
//            btnEntertain.setEnabled(false);
//            btnHealthnews.setEnabled(false);
//            clearNotification();
//            initPermissions();
//            viewMask.setVisibility(View.VISIBLE);
//        }
    }

    /**
     * 6.0权限处理
     */
    private void initPermissions()
    {

        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            getRxPermissions() // requestEach会发送两个Permission对象
                .requestEach(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe((Permission permission) -> {// 在android 6.0之前会默认返回true
                    if (permission.granted)
                    { // 2个权限都已经获取

                    }
                    else if (permission.name.equals(Manifest.permission.READ_PHONE_STATE))
                    {
                        permissionsList.add(Manifest.permission.READ_PHONE_STATE);
                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                            REQUEST_PHONE_PERMISSIONS);
                    }
                    else if ((permission.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)))
                    {
                        permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                            REQUEST_PHONE_PERMISSIONS);
                    }
                });
        }

    }

    private void initImSDK()
    {

        RefreshEvent.getInstance(); // 设置IM事件刷新监听
        // 从TLS缓存获取最新的用户账号（如果有，也有可能没有）
        String imAccount = TLSService.getInstance().getLastUserIdentifier();
        ImUser.getInstance().setImAccount(imAccount);
        // 从腾讯后台获取用户凭证并且保存
        ImUser.getInstance().setImSign(TLSService.getInstance().getUserSig(imAccount));
    }

    /**
     * 直接登录IM
     */
    @Override
    public void loginIm()
    {
        LoginImService.getInstance().loginIm();
    }

    /**
     * 登录Tls
     */
    @Override
    public void loginTls()
    {
        /* 防止空指针 */
        if (null == DataManager.getInstance().getUser().getImAccount())
        {
            return;
        }
        String imAccount = DataManager.getInstance().getUser().getImAccount();
        LoginImService.getInstance().loginTls(imAccount, ApiConfigs.IM_USER_PASSWORD);
    }

    /**
     * 是否已有用户登录
     */
    @Override
    public boolean isUserLogin()
    {
        return LoginImService.getInstance().isUserLogin();
    }

    /**
     * 清楚所有通知栏通知
     */
    private void clearNotification()
    {
        NotificationManager notificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    /**
     * 权限处理返回
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        switch (requestCode)
        {
            case REQUEST_PHONE_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    initImSDK();
                }
                else
                {
                    getvDelegate().toastShort(ResourceUtil.getResources().getString(R.string.need_permission));
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    // 点击事件
    @OnClick({R.id.btn_control, R.id.btn_userHome, R.id.btn_his, R.id.btn_phyCharge, R.id.btn_life, R.id.btn_nures,
        R.id.btn_entertain, R.id.btn_Healthnews})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.btn_control:
                confirmAsHomeFragment(Constants.NUM_CONTROIL,
                    ResourceUtil.getResources().getString(R.string.splash_item_bedControl));
                break;
            case R.id.btn_userHome:
                confirmAsHomeFragment(Constants.NUM_USERHOME,
                    ResourceUtil.getResources().getString(R.string.splash_item_userHome));
                break;
            case R.id.btn_his:
                confirmAsHomeFragment(Constants.NUM_HIS,
                    ResourceUtil.getResources().getString(R.string.splash_item_his));
                break;
            case R.id.btn_phyCharge:
                confirmAsHomeFragment(Constants.NUM_PHYCHARGE,
                    ResourceUtil.getResources().getString(R.string.splash_item_phyCharge));
                break;
            case R.id.btn_life:
                confirmAsHomeFragment(Constants.NUM_LIFEDATA,
                    ResourceUtil.getResources().getString(R.string.splash_item_life));
                break;
            case R.id.btn_nures:
                confirmAsHomeFragment(Constants.NUM_NURSE_HELP,
                    ResourceUtil.getResources().getString(R.string.splash_item_nures));
                break;
            case R.id.btn_entertain:
                confirmAsHomeFragment(Constants.NUM_ENTERTAIN,
                    ResourceUtil.getResources().getString(R.string.splash_item_entertain));
                break;
            case R.id.btn_Healthnews:
                confirmAsHomeFragment(Constants.NUM_HEALTHNEWS,
                    ResourceUtil.getResources().getString(R.string.splash_item_Healthnews));
                break;
            default:
                confirmAsHomeFragment(Constants.NUM_DEFAULT,
                    ResourceUtil.getResources().getString(R.string.splash_item_bedControl));
                break;
        }
    }

    public void confirmAsHomeFragment(int pageValue, String fragmentName)
    {

        new DialogIosAlert(SplashActivity.this).builder()
            .setTitle("提示小Tips")
            .setMsg("  您要将 " + fragmentName + "页面作为你的初始页面吗？")
            .setNegativeButton(ResourceUtil.getResources().getString(R.string.cancel), view -> {
                getvDelegate().toastShort("你取消了操作！");
            })
            .setPositiveButton(ResourceUtil.getResources().getString(R.string.confirm), view -> {

                getP().savaPageValue(pageValue);
                MainActivity.launch(SplashActivity.this, pageValue);
//                HomeActivity.launch(SplashActivity.this, pageValue);
            })
            .show();
    }

}